<?php

namespace App\Http\Middleware;

use App\Jobs\OperationLogJob;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class UserLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        Log::channel('requestlog')->info("========请求开始========");
        $time1 = microtime(true);
        $response = $next($request);
        $time2 = microtime(true);
        try{
            //请求方式
            $method = $request->method();
            Log::channel('requestlog')->info("请求方式：".$method);
            //请求路径
            $path = $request->getPathInfo();
            Log::channel('requestlog')->info("请求地址：".$path);
            //IP地址
            $ip = get_client_ip();
            Log::channel('requestlog')->info("IP地址：".$ip);
            // 剔除GET，OPTIONS请求
            if(!in_array($method,['OPTIONS','GET'])) {
                if(!empty($response->getContent()) && $response->status() == 200){
                    $res = 1;
                    Log::channel('requestlog')->info("请求结果：SUCCESS");
                }else{
                    $res = 2;
                    Log::channel('requestlog')->info("请求结果：ERROR");
                }
                $user_id = $request->user_id;
                if($path == '/api/signIn'){
                    $user_id = $response->original['data']['id'];
                }
                Log::channel('requestlog')->info("USER_ID：".$user_id);
                $run_time = sprintf("%.4f",($time2-$time1)).'秒';
                Log::channel('requestlog')->info("运行时间：".$run_time);
                $data = [
                    'user_id' => $user_id,
                    'path' => $path,
                    'method' => $method,
                    'ip' => $ip,
                    'res'=>$res,
                    'run_time'=>$run_time,
                    //'response'=>\json_encode($response->getContent(), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE),
                    'input' => \json_encode($request->all(), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE),
                    'route_name' => $request->route()->getName()
                ];

                // 异步写入，提高操作流畅性
                $job = (new OperationLogJob($data));
                dispatch($job);
                Log::channel('requestlog')->info("========请求结束========");
            }
            return $response;

        }catch(\Exception $exception){
            return re(2001,'',$exception->getMessage());
        }




    }
}
